package main

import (
	"context"
	"fmt"
	"github.com/mongodb/mongo-go-driver/bson/objectid"
	"github.com/mongodb/mongo-go-driver/mongo"
	"github.com/mongodb/mongo-go-driver/mongo/options"
	"time"
)

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type LogRecord struct {
	JobName   string    `bson:"jobName"`
	Command   string    `bson:"command"`
	Err       string    `bson:"err"`
	Content   string    `bson:"content"`
	TimePoint TimePoint `bson:"timePoint"`
}

func main() {
	var (
		mongo_uri  string
		opts       *options.ClientOptions
		client     *mongo.Client
		err        error
		database   *mongo.Database
		collection *mongo.Collection
		record     *LogRecord
		result     *mongo.InsertOneResult
		logArr     []interface{}
		result2    *mongo.InsertManyResult
	)
	// 1. 建立连接
	mongo_uri = "mongodb://127.0.0.1:27017"
	opts = options.Client()
	opts.SetConnectTimeout(5 * time.Second)
	if client, err = mongo.Connect(context.TODO(), mongo_uri, opts); err != nil {
		fmt.Println(err)
		return
	}
	// 2. 选择数据库 my_db
	database = client.Database("cron")
	// 3. 选择表 my_collection
	collection = database.Collection("logs")

	// 4 插入一条数据
	record = &LogRecord{
		JobName: "job10",
		Command: "echo hello",
		Err:     "",
		Content: "hello",
		TimePoint: TimePoint{
			StartTime: time.Now().Unix(),
			EndTime:   time.Now().Unix() + 10,
		},
	}
	if result, err = collection.InsertOne(context.TODO(), record); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("自增ID", result.InsertedID.(objectid.ObjectID).Hex())

	// 5 批量插入多条
	logArr = []interface{}{record, record, record}
	if result2, err = collection.InsertMany(context.TODO(), logArr); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(result2.InsertedIDs)

}
